package com.manlitech.cloudboot.oauth.util;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.SignatureAlgorithm;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * jwt令牌生产工具
 * @author shensg
 * @date 2021/7/7 18:10
 */
@Component
public class JwtTokenUtil implements Serializable {
    //生产jwt
    public static String build(String username, String telephone, List<String> roles) {
        //签名算法，选择SHA-256
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        String signKey = "NDU0NTY4amhmc3NkeHp6eGNxdzIlMjFAJTIxQCUyM2ZmNQ==";//盐

        //获取当前系统时间
        Date now = new Date(System.currentTimeMillis());
        Date exp = new Date(System.currentTimeMillis() + 1000 * 60 * 60);
        JSONObject payLoad = new JSONObject();
        payLoad.put("username", username);
        payLoad.put("telephone", telephone);
        payLoad.put("roles", roles);
        //jwt
        JwtBuilder jwt = io.jsonwebtoken.Jwts.builder()
                .setClaims(payLoad)//自定义内容
                .setId(UUID.randomUUID().toString()) //每个jwt的唯一标识
                .setIssuedAt(now)        //签发时间
                .setExpiration(exp)       //过期时间
                .setSubject(username)    //可以放用户名，用户唯一标识
                .signWith(signatureAlgorithm, signKey);
        String compact = jwt.compact();

        return compact;
    }
}

